using System;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace UDS.Web.UI.Controls
{
    /// <summary>
    /// This control allows an end user to upload several files at a time.
    /// </summary>
    [ToolboxData(@"<{0}:FileUploader runat=""server"" />")]
    public class FileUploader : WebControl
    {
        #region WebControl members

        /// <summary>
        /// This method overrides <see cref="Control.OnPreRender"/>.
        /// </summary>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (Page != null)
            {
                HtmlForm form = Page.Form;
                if (form != null && form.Enctype.Length == 0)
                {
                    form.Enctype = "multipart/form-data";
                }
            }
        }

        /// <summary>
        /// This method overrides <see cref="WebControl.Render(HtmlTextWriter)"/>.
        /// </summary>
        protected override void Render(HtmlTextWriter writer)
        {
            if (Page != null)
            {
                // This control must be resided in a server form.
                Page.VerifyRenderingInServerForm(this);

                // Only one FileUploader control is allowed in a page.
                if (Page.Items[s_fileUploaderRendered] != null)
                {
                    throw new InvalidOperationException("Only one FileUploader control is allowed in a page.");
                }
                else
                {
                    Page.Items[s_fileUploaderRendered] = true;
                }
            }

            // Renders the required javascript
            writer.Write("<script type=\"text/javascript\">\r\n");
            writer.Write(string.Format("var FileUploader_Max={0};\r\n", _maxFileCount));
            writer.Write("var FileUploader_IC_Remove=\"删除\";\r\n");
            writer.Write("</script>");
            writer.Write(s_scriptBlock);

            writer.WriteBeginTag("DIV");
            writer.WriteAttribute("id", ClientID + "$Attachments");
            writer.Write("></DIV>\r\n");

            writer.WriteBeginTag("A");
            writer.WriteAttribute("id", ClientID);
            writer.WriteAttribute("href", "javascript:void(0);");
            writer.WriteAttribute("onclick", "FileUploader_A(this);");
            writer.Write('>');
            if (Page != null)
            {
                writer.WriteBeginTag("IMG");
                writer.WriteAttribute("border", "0");
                writer.WriteAttribute("align", "absMiddle");
                writer.WriteAttribute("src", ResolveUrl("~/images/attach.gif"));
                writer.Write("/>");

                writer.Write(_text);
                if (_maxFileCount == 1)
                {
                    writer.Write("(只允许一个文件)");
                }
                else if (_maxFileCount > 1)
                {
                    writer.Write(string.Format("(最多 {0} 个文件)", _maxFileCount));
                }
            }
            writer.Write("</A>");
        }

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes an instance of this class.
        /// </summary>
        public FileUploader()
        {
            _maxFileCount = 8;
            _text = "添加附件";
        }

        #endregion

        #region Methods

        /// <summary>
        /// Save the posted files.
        /// </summary>
        /// <remarks>
        /// If the path <i>stStorePath</i> does not exist, the method will create it.
        /// </remarks>
        public void Save(string stPhysicalPath)
        {
            HttpFileCollection files = Files;
            if (files == null || files.Count == 0)
            {
                return;
            }

            // Ensure that the path exists
            //
            Directory.CreateDirectory(stPhysicalPath);

            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile f = files[i];
                if (string.IsNullOrEmpty(f.FileName) || f.ContentLength == 0)
                {
                    continue;
                }

                string filename = Path.GetFileName(f.FileName);
                f.SaveAs(Path.Combine(stPhysicalPath, filename));
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets all the posted files.
        /// </summary>
        public HttpFileCollection Files
        {
            get { return Context.Request.Files; }
        }

        /// <summary>
        /// Gets or sets the text of this control.
        /// </summary>
        public string Text
        {
            get { return _text; }
            set { _text = value; }
        }

        /// <summary>
        /// The max number of files that are allowed to be uploaded once.
        /// </summary>
        public int MaxFileCount
        {
            get { return _maxFileCount; }
            set
            {
                if (_maxFileCount <= 0)
                {
                    throw new ArgumentOutOfRangeException("value");
                }
                _maxFileCount = value;
            }
        }

        #endregion

        #region Fields

        private int _maxFileCount;
        private string _text;

        private const string s_fileUploaderRendered = "FileUploader_Exists";
        private const string s_scriptBlock = @"
<script type=""text/javascript"">
var FileUploader_Count=0;
var FileUploader_Index=0;
function FileUploader_A(elm){
 var d=document.createElement('DIV');document.getElementById(elm.id+'$Attachments').appendChild(d);d.attachLink=elm;d.innerHTML=""<a href='javascript:void(0);' onclick='FileUploader_R(this)'>""+FileUploader_IC_Remove+""</a><span>&nbsp;&nbsp;</span><input type=file name='""+elm.id+""$""+(++FileUploader_Index)+""' onchange='FileUploader_C(this)' /><span></span>"";
 FileUploader_Count ++;
 if(FileUploader_Max>0 && FileUploader_Max<=FileUploader_Count){h(elm);}
 elm.blur();d.childNodes[2].focus();
}
function FileUploader_R(elm){FileUploader_Count--;var d=elm.parentNode;var k=d.attachLink;var path=d.childNodes[3].innerHTML;d.parentNode.removeChild(d);h1(k);FileUploader_FileRemoved(path);}
function FileUploader_C(elm){var path=elm.value;if(path==''){return;}elm.parentNode.childNodes[3].innerHTML=path;h(elm);FileUploader_FileAdded(path);}
function h(e){if(e&&e.style){var s=e.style;s.display='none';s.visibility='hidden';}}
function h1(e){if(e&&e.style){var s=e.style;s.display='';s.visibility='visible';}}
function FileUploader_FileAdded(path){}
function FileUploader_FileRemoved(path){}
</script>
";

        #endregion
    }
}